<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Pc_Api_V2_Guide_Index extends Controller_Pc_Api_V2_Base
{
    //用户id

    private $result;
    private $typeid = 106;
    public function before()
    {
        parent::before();
        // 检查会员信息
        $token       = Common::remove_xss($this->request_data->token);
        $check_token = Model_Api_V2_Pub::token_decode($token);
        if ($check_token['status']) {
            $this->mid = $check_token['mid'];
        }
        $this->request_param = array_map(function ($item) {
            return Common::remove_xss($item);
        }, (array)$this->request_data);
        $this->result = array(
            'status' => true,//默认状态为成功
            'msg' => '操作成功',//默认的提示消息
            'data' => array()
        );
    }
    /**
     * 获取推荐导游
     */
    public function action_recommend()
    {
        $page   = $this->request_data->page;
        $row    = $this->request_data->pagesize;
        $page   = $page > 0 ? $page : 1;
        $row    = $row > 0 ? $row : 10;
        $offset = ($page - 1) * $row;
        $field = 'sg.id,sg.mid,sg.work_time,sg.guide_card_id,sg.good_language,sg.service_city,sm.litpic';
        $sql   = "SELECT " . $field . " FROM sline_guide as sg join sline_member as sm on sm.mid = sg.mid where sm.mid>0 and sg.status =1 ";
        $sql   .= "order by displayorder limit {$offset},{$row}";
        $result = DB::query(Database::SELECT, $sql)->execute()->as_array();

        foreach ($result as $k => &$v) {
            $member = DB::select('litpic')->from('member')->where('mid','=',$v['mid'])->execute()->current();
            $v['title'] = $member['nickname'];
            $v['mobile'] = $member['mobile'];
            $v['litpic']  = Model_Api_V2_System::uniapp_img($member['litpic'], 138, 94);
        }
        $this->result['data'] = $result;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }



    //搜索条件
    public function action_query_condition()
    {

        $result = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '产品推荐')
            ),
            'attribute' => array(),
            'price' => array('name' => '价格', 'child' => array()),
        );
        //属性
        $result['attribute'] = DB::select('id', array('attrname', 'name'))
            ->from('guide_attr')
            ->where('pid', '=', 0)
            ->and_where('isopen', '=', 1)
            ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
            ->execute()
            ->as_array();
        foreach ($result['attribute'] as &$item)
        {
            $item['child'] = DB::select('id', array('attrname', 'name'))
                ->from('guide_attr')
                ->where('pid', '=', $item['id'])
                ->and_where('isopen', '=', 1)
                ->order_by(DB::expr('ifnull(displayorder,9999)'), 'asc')
                ->execute()
                ->as_array();
        }
        $result['price']['child'] = DB::select()->from('guide_pricelist')
            ->where('lowerprice', '>=', 0)
            ->order_by('lowerprice', 'asc')
            ->execute()
            ->as_array();
        //价格
        foreach ($result['price']['child'] as &$row)
        {
            if ($row['lowerprice'] == 0 && $row['highprice'] != 0)
            {
                $row['name'] = Currency_Tool::symbol() . $row['highprice'] . '以下';
            }
            else if ($row['highprice'] == '' || $row['highprice'] == 0)
            {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '以上';
            }
            else if ($row['lowerprice'] != '' && $row['highprice'] != '')
            {
                $row['name'] = Currency_Tool::symbol() . $row['lowerprice'] . '-' . Currency_Tool::symbol() . $row['highprice'];
            }
        }
        $this->result['data'] = $result;
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    //查询服务列表
    public function action_query()
    {

        try {
            $validataion = Validation::factory($this->request_param);
            $validataion->rule('page', 'not_empty');
            $validataion->rule('pagesize', 'not_empty');
            if (!$validataion->check())
            {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }
            $params = $this->request_param;
            $route_array = array(
                'destpy'   => is_null($params['destpy']) ? 'all' : $params['destpy'],
                'priceid'  => is_null($params['priceid']) ? 0 : intval($params['priceid']),
                'sex'      => 2,
                'sorttype' => is_null($params['sorttype']) ? 0 : intval($params['sorttype']),
                'attrid'   => is_null($params['attrid']) ? 0 : $params['attrid'],
                'p'        => $params['page'] > 0 ? $params['page'] : 1,
                'keyword'  => $params['keyword'],
            );


            $this->result = array('status' => true, 'data' => Model_Api_V2_Guide::search_result($route_array, $params['page'], $params['pagesize']));
        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage(), 'data' => $this->request_param);
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    // 导游所能提供服务
    public function action_get_guide_service()
    {
        try {
            $validataion = Validation::factory($this->request_param);
            $validataion->rule('guide_id', 'not_empty');
            $validataion->rule('page', 'not_empty');
            $validataion->rule('pagesize', 'not_empty');
            if (!$validataion->check()) {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }
            $obj = DB::select()->from('guide_service')->where('status', '=', 6)->and_where('guide_id', '=', $this->request_param['guide_id']);
            $total = clone $obj;
            $data = $obj->limit($this->request_param['pagesize'])->offset(($this->request_param['page'] - 1) * $this->request_param['pagesize'])->order_by('id', 'desc')->execute()->as_array();

            $out = [];
            foreach ($data as &$item) {
                $guide = DB::select()->from('guide')->where('id','=',$item['guide_id'])->execute()->current();
                $member = DB::select()->from('member')->where('mid','=',$guide['mid'])->execute()->current();
                $out[] = array(
                    'id' => $item['id'],
                    'litpic' => Model_Api_V2_System::uniapp_img($item['litpic']),
                    'title' => $item['title'],
                    'price' => $item['price'],
                    'guide' => $member['nickname']
                );

            }
            $this->result = array('status' => true, 'data' => array('total'=>$total->execute()->count(),'list'=>$out));
        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage());
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    // 服务详情
    public  function action_service_show()
    {
        try {
            $validataion = Validation::factory($this->request_param);
            $validataion->rule('id', 'not_empty');
            if (!$validataion->check()) {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }
            $service = Model_Guide_Service::get_info($this->request_param['id']);



            if(!isset($service['id']))
            {
                throw new Exception(__("未找到服务"));
            }
            //排队不需要项
            unset($service['aid'],
                $service['webid'],
                $service['color'],
                $service['seotitle'],
                $service['keyword'],
                $service['description'],
                $service['tagword'],
                $service['ishidden'],
                $service['paytype'],
                $service['iconlist'],
                $service['themelist'],
                $service['supplierlist'],
                $service['templet'],
                $service['dingjin'],
                $service['jifenbook_id'],
                $service['jifentprice_id']
            );
            //导游详情
            $guide = DB::select()->from('guide')->where('id','=',$service['guide_id'])->execute()->current();
            $uinfo = Model_Member::get_member_info($guide['mid']);
            $service['guide']['title'] = $uinfo['truename'];
            $service['guide']['litpic'] = Model_Api_V2_System::uniapp_img($uinfo['litpic']);
            $contacts_status = Model_Guide::check_contacts_show($guide['id'],$guide['mid']);
            $service['guide']['mobile'] = $contacts_status==2?$uinfo['mobile']:Model_Guide::complex_mobile($uinfo['mobile']).(预约导游即可见号码);
            $service['guide']['service_city'] = $guide['service_city'];
            $service['enable_book'] = ($service['start_time'] > time() || $service['end_time'] < time()) ? 0 : 1;
            $piclist = $service['piclist'];
            $new_img = array();
//            foreach ($piclist as &$v){
//                $img = Model_Api_V2_System::uniapp_img($v[0]);
//                array_push($new_img,$img);
//            }
//            $service['piclist'] = $new_img;
            $this->result = array('status' => true, 'data' => $service);
        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage());
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);

    }

    // 获取导游详情
    public function action_show()
    {
        try {
            $validataion = Validation::factory($this->request_param);
            $validataion->rule('id', 'not_empty');
            if (!$validataion->check()) {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }
            $guide = DB::select()->from('guide')->where('id', '=', $this->request_param['id'])->execute()->current();
            if ($guide) {
                $this->result = array('status' => true, 'data' => Model_Api_V2_Guide::info($this->request_param['id']));
            } else {
                throw new Exception(__('导游不存在'));
            }
        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage());
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    /**
     * 日历报价
     * @throws Exception
     */
    public function action_calendar()
    {
        $service_id = $this->request_param['service_id'];
        if(!$service_id)
        {
            throw new Exception(__("服务id不能为空"));
        }
        $data = Model_Guide_Suit_Price::calendar($service_id);
        $this->result = array('status' => true, 'data' => $data);
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }
    // 添加订单
    public function action_add_order()
    {
        try {
            $validataion = Validation::factory($this->request_param);
            $validataion->rule('product_id', 'not_empty');
            $validataion->rule('linkman', 'not_empty');
            $validataion->rule('linktel', 'not_empty');
            $validataion->rule('source', 'not_empty');
            $validataion->rule('usedate', 'not_empty');
            //$validataion->rule('memberid', 'not_empty');
            if (!$validataion->check()) {
                $error = $validataion->errors();
                $keys = array_keys($validataion->errors());
                throw new Exception(__("error_{$keys[0]}_{$error[$keys[0]][0]}"));
            }
            $useDay = strtotime($this->request_param['usedate']);
            $totalPrice = 0;
            $guide_service = DB::select()->from('guide_service')
                ->where('id', '=', $this->request_param['product_id'])
                ->execute()
                ->current();
            $service_price = DB::select()->from('guide_service_price')
                ->where('service_id', '=', $this->request_param['product_id'])
                ->and_where('day', '=', $useDay)
                ->and_where('number', '=', 1)
                ->execute()
                ->current();
            if(!isset($service_price['id']))
            {
                throw new Exception("库存不足");
            }
            $member = Model_Member::get_member_info($this->mid);
            if(!isset($member['mid']))
            {
                throw new Exception("未找到会员");
            }

            $order = array(
                'webid' => 0,
                'addtime' => time(),
                'typeid' => $this->typeid,
                'ordersn' => St_Product::get_ordersn("{$this->typeid}"),
                'litpic' => $guide_service['litpic'],
                'productaid' => $guide_service['aid'],
                'productname' => $guide_service['title'],
                'price' => $guide_service['price'],
                'suit_name' => $guide_service['title'],
                'paytype' => $guide_service['paytype'],
                'dingjin' => $guide_service['paytype'] == 2 ? $guide_service['dingjin'] : 0,
                'childprice' => 0,
                'childnum' => 0,
                'oldprice' => 0,
                'oldnum' => 0,
                'need_confirm' => 0,
                'status' => $guide_service['paytype'] != 3 ? 1 : 0,
                'auto_close_time' => 0,
                'productautoid' => $this->request_param['product_id'],
                'dingnum' => 1,
                'suitid' => 0,
                'source' => $this->request_param['source'],
                'usedate' => $this->request_param['usedate'],
                'linkman' => $this->request_param['linkman'],
                'linktel' => $this->request_param['linktel'],
                'linkemail' => empty($this->request_param['linkemail']) ? '' : $this->request_param['linkemail'],
                'remark' => $this->request_param['remark'],
                'memberid' => $this->mid,
                'jifenbook' => $guide_service['jifenbook_id'],
                'jifencomment' => ($comment = Model_Jifen::get_used_jifencomment($this->type_id)) ? 0 : $comment['value'],
            );
            //优惠券
            if ($coupon_id = $this->request_param['coupon_id']) {
                $cid = DB::select('cid')->from('member_coupon')->where("id={$coupon_id}")->execute()->current();
                $totalprice = (new Model_Coupon())->get_order_totalprice(array_merge($order, array('childnum' => 0, 'oldnum' => 0, 'childprice' => 0, 'oldprice' => 0)));
                $ischeck = Model_Api_V2_Coupon::check_samount($coupon_id, $totalprice, $order['typeid'], $order['productautoid'], strtotime($order['usedate']),$this->member_id);
                if ($ischeck['status'] == 1) {
                    (new Model_Coupon())->add_coupon_order($cid, $order['ordersn'], $totalprice, $ischeck, $coupon_id);
                } else {
                    throw new Exception(__("优惠券不可用"));
                }
            }
            //写入订单
            if ($result = Model_Api_V2_Order::add_order($order, 'Model_Guide') and $result['status']) {
                $order_info = Model_Member_Order::order_info($order['ordersn']);
                //红包
                if (St_Functions::is_normal_app_install('red_envelope') && $this->request_param['envelope_member_id']) {
                    Model_Order_Envelope::order_use_envelope($this->request_param['envelope_member_id'], $order['ordersn'], $this->type_id, $order_info['memberid']);
                }
                //订单结算信息表数据更新
                Model_Member_Order_Compute::update($order['ordersn']);
                //写导游订单表
                $guide_order = array(
                    'ordersn' => $order['ordersn'],
                    'guide_id' => $guide_service['guide_id'],
                    'people_num' => $guide_service['service_number'],
                    'award' => Model_Guide::get_award($order['ordersn'],$order_info['pay_price'])
                );
                list($id,$flag) = DB::insert('guide_order',array_keys($guide_order))->values(array_values($guide_order))->execute();
                $this->result = array('status' => true, 'data' => $order_info);

            } else {
                throw new Exception(__($result['msg']));
            }


        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage());
        }
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);

    }



}
